package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.config.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.GetUserInfoUtil;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.UserInfo;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 万能键 alt + enter
 */
@Service //交给spring管理
public class EmployeeServiceImpl extends BaseServiceImpl<Employee,EmployeeQuery> implements IEmployeeService {

    /**
     * 注入mapper层对象
     */
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 登录逻辑
     * @param employee
     * @return
     */
    @Override
    public AjaxResult login(Employee employee) {
        //1.根据用户名匹配,查询用户对象
        Employee dbEmployee = employeeMapper.findByUsername(employee);
        if (dbEmployee == null){
            throw new BusinessException("账号名与密码不匹配，请重新输入111111111111");
        }

        //2.比对密码
        //2.1把页面的密码进行加盐加密,和数据库查到的密码串进行比对
        String password = employee.getPassword();
        String salt = dbEmployee.getSalt();
        String pagePwd = MD5.create().setSalt(salt.getBytes()).digestHex(password);
        if (!StringUtils.equals(pagePwd,dbEmployee.getPassword())){
            throw new BusinessException("账号名与密码不匹配，请重新输入22222222222");
        }

        //3.redis存 key :uuid(token)  value:用户信息(兼容管理员employee,消费者user,.用公共UserInfo对象)     时间:30分钟
        String token = IdUtil.fastSimpleUUID();

        //3.1bean拷贝
        UserInfo userInfo = BeanUtil.copyProperties(dbEmployee, UserInfo.class);
        userInfo.setToken(token);
        userInfo.setShopId(dbEmployee.getShopId());

        redisService.setStringKeyAndValue(token,userInfo,30);

        //4.返回 token ,用户对象
        return AjaxResult.createSuccess(userInfo);
    }

    @Override
    public List<Employee> findShopEmps() {

        //获取店铺的id
        Long shopId = GetUserInfoUtil.getShopId();
        //根据店铺的id获取店铺的员工们
        return employeeMapper.findShopEmps(shopId);
    }


    @Override
    public List<Employee> findManagers() {
        //调用
        return employeeMapper.findManagers();
    }



}
